package com.bckj.fastboot.iot.data.mongo.repository;

import com.bckj.fastboot.core.extra.mongo.AbstractMongoRepository;
import com.bckj.fastboot.core.extra.mongo.MongoOps;
import com.bckj.fastboot.core.lang.model.PageResult;
import com.bckj.fastboot.iot.common.dto.query.IotBasicDataQuery;
import com.bckj.fastboot.iot.common.dto.request.IotBasicDataRequest;
import com.bckj.fastboot.iot.common.dto.response.IotBasicDataResponse;
import com.bckj.fastboot.iot.common.repository.IotBasicDataRepository;
import com.bckj.fastboot.iot.data.mongo.convert.IotBasicDataConvert;
import com.bckj.fastboot.iot.data.mongo.entity.IotBasicData;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * IotBasicDataRepositoryImpl
 *
 * @author wfc
 **/
@Repository
public class IotBasicDataRepositoryImpl
    extends AbstractMongoRepository<IotBasicData, Long>
        implements IotBasicDataRepository {

    private final IotBasicDataConvert iotBasicDataConvert;

    public IotBasicDataRepositoryImpl(
            MongoOps mongoOps,
            IotBasicDataConvert iotBasicDataConvert
    ) {
        super(mongoOps, IotBasicData.class, "iot_basic_data");
        this.iotBasicDataConvert = iotBasicDataConvert;
    }

    @Override
    public boolean save(IotBasicDataRequest request) {
        var entity = iotBasicDataConvert.toEntity(request);
        return save(entity);
    }

    @Override
    public boolean updateById(IotBasicDataRequest request) {
        var entity = iotBasicDataConvert.toEntity(request);
        return updateById(entity);
    }

    @Override
    public IotBasicDataResponse details(Long id) {
        return findById(id, IotBasicDataResponse.class);
    }

    @Override
    public List<IotBasicDataResponse> findList(IotBasicDataQuery query) {
        return find(buildQuery(query), IotBasicDataResponse.class);
    }

    @Override
    public PageResult<IotBasicDataResponse> page(Pageable page, IotBasicDataQuery query) {
        return page(page, buildQuery(query), IotBasicDataResponse.class);
    }

    private Query buildQuery(IotBasicDataQuery query) {
        var criteria = Criteria.where("devCode").is(query.getDevCode());
        if (query.getStartTime() != null) {
            criteria = criteria.and("collectionTime").gt(query.getStartTime());
        }
        if (query.getEndTime() != null) {
            criteria = criteria.and("collectionTime").lt(query.getEndTime());
        }
        return Query.query(criteria);
    }
}
